/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.morpheus.redis.lettuce.serializer;

import java.lang.reflect.ParameterizedType;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.IOUtils;

/**
 * Redis序列化
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0
 */
public class JsonRedisSerializer<T> implements RedisSerializer<T> {
	private static ParserConfig defaultRedisConfig = new ParserConfig();
	static {
		defaultRedisConfig.setAutoTypeSupport(true);
	}

	public JsonRedisSerializer() {
	}

	@Override
	public byte[] serialize(T t) throws SerializationException {
		if (t == null) {
			return new byte[0];
		}
		return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(IOUtils.UTF8);
	}

	@Override
	public T deserialize(byte[] bytes) throws SerializationException {
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		String str = new String(bytes, IOUtils.UTF8);

		Class<T> type = this.getTClass();
		return JSON.parseObject(str, type, defaultRedisConfig);
	}

	public Class<T> getTClass() {
		Class<T> tClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
				.getActualTypeArguments()[0];
		return tClass;
	}
}